package com.xnx3.spider.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.PageLoadStrategy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chromium.ChromiumDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.v114.fetch.Fetch;
import org.openqa.selenium.devtools.v114.network.Network;
import com.xnx3.BaseVO;
import com.xnx3.DateUtil;
import com.xnx3.FileUtil;
import com.xnx3.Log;
import com.xnx3.MD5Util;
import com.xnx3.StringUtil;
import com.xnx3.SystemUtil;
import com.xnx3.UrlUtil;
import com.xnx3.spider.Global;
import com.xnx3.spider.cache.Cache;
import com.xnx3.spider.cache.Resource;
import com.xnx3.spider.vo.ResourceVO;
import com.xnx3.spider.vo.ResponseVO;

import cn.zvo.http.Http;
import cn.zvo.http.Response;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class ChromeUtil {
	private ChromeDriver driver;
	static Map<String, String> headers;
	
	//这俩在application.properties配置
	static String chromePath;
	static String chromeDriverPath;
	
	static {
		chromePath = "G:\\git\\chromeTool\\bin\\chrome\\chrome.exe";
		chromeDriverPath="G:\\\\git\\\\chromeTool\\\\bin\\\\chrome\\chromedriver.exe";
		Log.info("chrome.path:"+chromePath);
		Log.info("chrome.driver.path:"+chromeDriverPath);
		
	}
	
	public static void main(String[] args) throws InterruptedException, IOException {
		
		ChromeUtil chrome = new ChromeUtil();
		ResponseVO vo = chrome.execute("https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap");
		System.out.println(vo.getMimeType());
		
	}
	
	/**
	 * 
	 * @param targetUrl 要打开的目标页面的url，要访问，也就是要翻译的目标页面的url，绝对地址
	 */
	//synchronized
	public ResponseVO execute(String targetUrl) {
		ResponseVO vo = null;
		try {
			vo = executeneibu(targetUrl);
		} catch (Exception e) {
			e.printStackTrace();
			vo = new ResponseVO();
			vo.setBaseVO(BaseVO.FAILURE, e.getMessage());
		}
		
		try {
			Thread.sleep(200);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		close();
		quit();
		
		return vo;
	}
	
	/**
	 * 
	 * @param targetUrl 要打开的目标页面的url，要访问，也就是要翻译的目标页面的url，绝对地址
	 * @param language
	 * @param newdomain 翻译后的使用的新域名，传入格式如 http://newdomain.zvo.cn   如果传入null，则代表不启用这个规则。
	 * @param executeJs 在执行页面翻译的操作时，额外执行的js。这个只是在翻译的过程中进行执行，影响的是输出的翻译结果 
	 * @throws InterruptedException
	 */
	//synchronized
	public ResponseVO executeneibu(String targetUrl) {
		ResponseVO vo = new ResponseVO();
		String html = "";
		
		driver = createDriver();
		
		
		DevTools devTools = ((ChromiumDriver) driver).getDevTools();
		devTools.createSession();
	    devTools.send(org.openqa.selenium.devtools.v114.network.Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));
//	    
//	    devTools.addListener(Network.requestWillBeSent(), entry -> {
//	    	Global.networkRequestUrlMap.put(url, entry.getRequest().getMethod());
//	                System.out.println( " ----- " 
//	                        + entry.getRequest().getUrl());
//	                String url = entry.getRequest().getUrl();
//	                Resource res = new Resource(url, targetUrl, "");
//					if(res.getNetUrl() != null){
//						ResourceVO resourceVO = Cache.addCache(res);
//						if(vo.getResult() - BaseVO.SUCCESS == 0){
//							System.out.println(" - ok---"+resourceVO.getResource().getLocalUrl());
//						}
//					}
//	                
//	            });
	    
	    devTools.addListener(Network.responseReceived(), entry -> {
//	                System.out.println("Response (Req id) URL : (" + entry.getRequestId() + ") " 
//	                        + entry.getResponse().getUrl()
//	                        + " (" + entry.getResponse().getStatus() + ")");
	    	String url = entry.getResponse().getUrl();        
	    	if(targetUrl.equalsIgnoreCase(entry.getResponse().getUrl())) {
            	//是当前的
            	vo.setMimeType(entry.getResponse().getMimeType());
            }
	    	
	    	
	    	try {
	    		Network.GetResponseBodyResponse response = devTools.send(Network.getResponseBody(entry.getRequestId()));
		        String body = response.getBody();
		        String[] v = {targetUrl,body};
		    	Global.networkRequestUrlMap.put(url,v);
		    	//Log.info( " ----- "  + url+",  size:"+body.length());
	    	}catch (Exception e) {
				//Global.log(e.getMessage()+", url:  "+url);
				e.printStackTrace();
	    	}
//	    	System.out.println(body);
	     }); 
		
		
		driver.get(targetUrl);
		
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		html = driver.getPageSource(); //获取源代码
		vo.setInfo(html);
		
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return vo;
	}
	

	public static String getLocalStorageSet(String key, String value) {
//		Log.info(value);
		return "localStorage.setItem(\""+key+"\",\""+value+"\");";
	}
	
	public void close() {
		Log.info("close driver : "+driver.toString());
		driver.close();
//		quit();
	}
	
	public void quit() {
		Log.info("quit driver : "+driver.toString()+"- "+DateUtil.timeForUnix10());
		driver.quit();
	}
	
	/**
	 * 创建 chrome 的 driver
	 * @return
	 */
	public ChromeDriver createDriver() {
		
		ChromeOptions options = new ChromeOptions(); // 设置chrome的一些属性
//		options.setPageLoadStrategy(PageLoadStrategy.NONE);
		options.addArguments("--disable-gpu"); //谷歌文档提到需要加上这个属性来规避bug
		options.addArguments("--ignore-certificate-errors");
		//options.addArguments("--disable-javascript"); //禁用javascript
		options.addArguments("--remote-allow-origins=*");//解决 403 出错问题
		Map<String, Object> prefs = new HashMap<String, Object>();
//		prefs.put("profile.managed_default_content_settings.images",2); //禁止下载加载图片
//		prefs.put("profile.managed_default_content_settings.javascript",2); //禁止下载加载js文件、执行js文件
//		prefs.put("profile.managed_default_content_settings.js",2); //禁止下载加载js文件、执行js文件
//		prefs.put("profile.managed_default_content_settings.css",2); //禁止下载加载js文件、执行js文件
//		
		
		options.setExperimentalOption("prefs", prefs);
		options.addArguments("disable-infobars");	//正受到自动测试软件的控制
		
		
		options.setBinary(chromePath);
		System.setProperty("webdriver.chrome.driver",chromeDriverPath);
		if(SystemUtil.isWindowsOS()) {
		}else {
			//centos中是将它放在了 /mnt/translate/chrome/
			//(unknown error: DevToolsActivePort file doesn't exist)
			options.addArguments("--disable-dev-shm-usage"); // overcome limited resource problems
			options.addArguments("--no-sandbox"); //数是让Chrome在root权限下跑
			
			//这种方式在无头Headless模式下是生效的， 非无头Headless模式下也是生效的。
//			options.addArguments("blink-settings=imagesEnabled=false");
//			options.addArguments("--headless"); //无界面运行 ,开启这个后js会被执行----------
		}
		
		options.addArguments("--headless"); //无界面运行 ,开启这个后js会被执行----------
//		options.addArguments("--disable-web-security");
//		options.addArguments("--allow-running-insecure-content");
		Log.info(JSONObject.fromObject(options).toString());
		//options.setPageLoadStrategy(PageLoadStrategy.EAGER);
		Log.info("webdriver.chrome.driver:"+System.getProperty("webdriver.chrome.driver"));
		driver = new ChromeDriver(options);
		Log.info("create driver : "+driver.toString());
		return driver;
	}
	
}
